<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/19 下午3:20
 *  * ============================================================================.
 */

namespace app\common\controller;

use app\BaseController;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Cookie;
use think\facade\Lang;
use think\Validate;
use think\facade\View;
use think\facade\Event;
use think\facade\Config;
use app\common\library\Auth;
use app\common\library\traits\Jump;
use think\exception\ValidateException;

/**
 * 前台控制器基类.
 */
class BaseFront extends BaseController
{
    /**
     * 布局模板
     *
     * @var string
     */
    protected $layout = 'default';

    public $suffix='';
    /**
     * 无需登录的方法,同时也就不需要鉴权了.
     *
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录.
     *
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth.
     *
     * @var Auth
     */
    protected $auth = null;

    protected $view;

    use Jump;
    /**
     * 构造方法.
     *
     * @param App $app 应用对象
     */
    public function __construct(protected App $app)
    {
        parent::__construct($app);
        $this->request = $this->app->request;
        $this->view = $this->app->view;
        $this->assign('site',['version'=>time()]);
        $this->assign('title',config('site.site_name'));
        // 控制器初始化
        $this->initialize();
    }
    protected function assign($name, $value = null)
    {
        View::assign($name, $value);
    }
    protected function initialize(): void
    {
        $this->auth = Auth::instance();
        // 如果有使用模板布局
        if ($this->layout) {
            View::engine()->layout('layout/'.$this->layout);
        }
        $routePath  = $this->app->request->controllerPath . '/' . $this->request->action(true);
        $token      = $this->request->server('HTTP_BA_USER_TOKEN', $this->request->request('ba-user-token', Cookie::get('ba-user-token') ?: false));
        if (!action_in_arr($this->noNeedLogin)) {
            $this->auth->init($token);
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }
            if (!action_in_arr($this->noNeedPermission)) {
                if (!$this->auth->check($routePath)) {
                    $this->error(__('You have no permission'), [], 401);
                }
            }
        } elseif ($token) {
            try {
                $this->auth->init($token);
            } catch (HttpResponseException) {
            }
        }
        $this->assign('title','站点名称');
        $this->assign('keywords','站点关键词');
        $this->assign('description','站点描述');
        $this->assign('site',config('site'));
        // 会员验权和登录标签位
        Event::trigger('frontendInit', $this->auth);
    }

    /**
     * 加载语言文件.
     *
     * @param string $name
     */
    protected function loadlang($name)
    {
        if (strpos($name, '.')) {
            $_arr = explode('.', $name);
            if (count($_arr) == 2) {
                $path = $_arr[0].'/'.parseName($_arr[1]);
            } else {
                $path = strtolower($name);
            }
        } else {
            $path = parseName($name);
        }
        Lang::load(app()->getAppPath().'/lang/'.Lang::getLangset().'/'.$path.'.php');
    }

    /**
     * 渲染配置信息.
     *
     * @param mixed $name  键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [],
            is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->post('__token__');

        //验证Token
        if (!Validate::is($token, "token", ['__token__' => $token])) {
            $this->error(__('Token verification error'), '', ['__token__' => $this->request->buildToken()]);
        }

        //刷新Token
        $this->request->buildToken();
    }

    //自定义视图模板路径
    private function templateHandle(){
        $mob=is_mobile();
        $views_dir=$mob?"mobile":"pc";//手机电脑模板判断处理手机电脑视图模板路径
        if(!config('app.is_mobile')){//判断是否开启手机模板
            $views_dir='pc';
        }
        $views_dir='pc';
        $path=[resource_path ('views/'.$views_dir)]; //获得文件夹路径
        View::setFinder (new FileViewFinder(App::make ('files'),$path));//改变模板的目录文件夹,指向我们给定的目录
    }
    //获取下级栏目
    public function getColumnChild($pid){
        $filde_arr=['route_name','pid','css','order','status','list_template','detail_template','id','title'.$this->suffix.' as  title','seo_desription'.$this->suffix.' as  seo_desription','seo_keywords'.$this->suffix.' as  seo_keywords'];
        $column_list=(new Column)->where(['status'=>1,'pid'=>$pid])->select($filde_arr)->orderBy('order','asc')->get();
        return $column_list;
    }
    public function getAllChild($pid){
        $cloumnModel=new Column();
        $filde_arr=['route_name','pid','css','order','status','list_template','detail_template','id','title'.$this->suffix.' as  title','seo_desription'.$this->suffix.' as  seo_desription','seo_keywords'.$this->suffix.' as  seo_keywords'];
        $all_li= $cloumnModel->where(['status'=>1])->select($filde_arr)->orderBy('order','asc')->get()->toArray();
        $tree_list= Tree::config(['pid'=>'pid'])->toLayer($all_li,$pid);
        return $tree_list;
    }
    //获取友情链接
    public function selectLinks(){
        $filde_arr=['id','icon_css','title','url','sort','status','title'.$this->suffix.' as  title'];
        return DB::table('landui_cms_links')->where(['status'=>1])->select($filde_arr)->orderBy('sort')->get();
    }
    //获取合作伙伴（校方合作）
    public function selectParter(){
        $lists= DB::table('landui_cms_parters')->where(['status'=>1])->orderBy('order')->get();
        return $lists;
    }
    /*获取属性*/
    public function getPartys($pid=0){
        $model= new Partys();
        $map=[];
        $filde_arr= ['id','cid','order','href','img','pid','name'.$this->suffix.' as  name','attributes'.$this->suffix.' as  attributes'];;
        if(!empty($pid)) $map['pid']=$pid;
        $reuslt= $model->where($map)->select($filde_arr)->orderBy('order')->get()->toArray();
        return $reuslt;
    }
    //获取导航连接
    public function getMenus($pid=1,$name='header_menus'){
        //  Cache::forget($name,null);
        return Cache::remember($name,60*24,function () use ($pid){
            $filde_arr=['parent_id','order','css','url','target','id','title'.$this->suffix.' as  title'];
            $list=MenuModel::where(['status'=>1])->orderBy('order','ASC')->get($filde_arr)->toArray();
            return Tree::config(['pid'=>'parent_id'])->Tolayer($list,$pid);
        });
    }
    //获取首页轮播图
    public function getSlider(){
        //  Cache::forget('sliders',null);
        //;
        $filde_arr=['cover','url','sort','status','title'.$this->suffix.' as  title','title_o'.$this->suffix.' as  title_o','title_t'.$this->suffix.' as  title_t'];
        return Cache::remember('sliders',60*24,function ()use($filde_arr){
            $list=DB::table('landui_cms_sliders')->where(['status'=>1])->orderBy('sort')->get($filde_arr)->toArray();
            return $list;
        });
    }
    //得到当前栏目信息
    public function  getColumnInfo($id,$filed="id"){
        $filde_arr=['route_name','pid','css','order','status','list_template','detail_template','id','title'.$this->suffix.' as  title','seo_title'.$this->suffix.' as  seo_title','detail'.$this->suffix.' as  detail','seo_desription'.$this->suffix.' as  seo_desription','seo_keywords'.$this->suffix.' as  seo_keywords'];
        $map=[];
        $map['status']=1;
        $map[$filed]=$id;
        return   (new App\Models\Column())->where($map)->select($filde_arr)->first();
    }
    public function getPages($route_name="home",$filed='route_name'){
        Cache::clear();
        return Cache::remember($route_name.$this->suffix,60*24,function () use($route_name,$filed){
            $filedArr=array_merge(['css','seo_title'.$this->suffix." as seo_title"],$this->files_arr);
            $pages=new Pages();
            $row=$pages->where([$filed=>$route_name])->select($filedArr)->first();
            return $row;
        });
    }

}
